﻿#include "campus_logger.h"

CampusLogger* CampusLogger::instance_ = new CampusLogger();

CampusLogger* CampusLogger::Instance() {
    return instance_;
}

// 构造函数：初始化默认日志配置
CampusLogger::CampusLogger() {
    
#ifdef _WIN32
    SetConsoleOutputCP(CP_UTF8);  
    SetConsoleCP(CP_UTF8);       
#endif

    try {
        // 默认使用控制台日志
        setDefaultLogger(LOGGER_CONSOLE);
        // 默认日志级别：INFO
        setLogLevel(LOG_INFO);
        // 默认日志格式
        setPattern("[%Y-%m-%d %H:%M:%S.%f] [%s:%#] [thread %t] [%^%L%$] %v");
    }
    catch (const std::exception& e) {
        throw std::runtime_error("CampusLogger初始化失败: " + std::string(e.what()));
    }
}

// 析构函数：清理日志资源
CampusLogger::~CampusLogger() {
    spdlog::shutdown();
    delete instance_;
    instance_ = nullptr;
}

// 转换日志级别
spdlog::level::level_enum CampusLogger::convertToSpdLevel(LogType level) {
    switch (level) {
        case LOG_TRACE:    return spdlog::level::trace;
        case LOG_DEBUG:    return spdlog::level::debug;
        case LOG_INFO:     return spdlog::level::info;
        case LOG_WARN:     return spdlog::level::warn;
        case LOG_ERROR:    return spdlog::level::err;
        case LOG_CRITICAL: return spdlog::level::critical;
        default:           return spdlog::level::info;
    }
}

// 设置日志级别
void CampusLogger::setLogLevel(LogType level) {
    auto spd_level = convertToSpdLevel(level);
    if (default_logger_) {
        default_logger_->set_level(spd_level);
    }
    spdlog::set_level(spd_level);
}

// 设置日志格式
void CampusLogger::setPattern(const std::string& pattern) {
    if (default_logger_) {
        default_logger_->set_pattern(pattern);
    }
    else {
        spdlog::set_pattern(pattern);
    }
}

// 设置默认日志器
bool CampusLogger::setDefaultLogger(LoggerSinkType logger_type,
    const std::string& file_path,
    size_t max_file_size,
    size_t max_files) {
    try {
        switch (logger_type) {
        case LOGGER_CONSOLE:
            default_logger_ = spdlog::stdout_color_mt("campus_console_logger");
            break;

        case LOGGER_FILE_BASIC:
            default_logger_ = spdlog::basic_logger_mt("campus_basic_file_logger", file_path);
            break;

        case LOGGER_FILE_ROTATING:
            default_logger_ = spdlog::rotating_logger_mt(
                "campus_rotating_logger",
                file_path,
                max_file_size,
                max_files
            );
            break;

        default:
            return false;
        }

        // 设置日志器为默认日志器
        spdlog::set_default_logger(default_logger_);
        return true;
    }
    catch (const spdlog::spdlog_ex& ex) {
        spdlog::error("设置日志器失败: {}", ex.what());
        return false;
    }
}
